package model

import (
	"gorm.io/gorm"
	"wechat01/handler/response"
)

type Friend struct {
	gorm.Model
	UserId   int    `gorm:"type:int" json:"userId"`
	FriendId int    `gorm:"type:int" json:"friendId"`
	Remark   string `gorm:"type:varchar(50)" json:"remark"`
	Status   int    `gorm:"type:int;default:0" json:"status"`
}

func (f *Friend) IsFriend(db *gorm.DB, userId int, friendId int) error {
	return db.Where("user_id = ? and friend_id = ?", userId, friendId).First(&f).Error
}
func (f *Friend) AddFriend(db *gorm.DB) error {
	return db.Create(&f).Error
}
func (f *Friend) FriendApply(db *gorm.DB, userId int, friendId int, status int) error {
	return db.Model(&f).Where("user_id = ? and friend_id = ?", userId, friendId).
		Update("status", status).Error
}

func (f *Friend) SearchFriend(db *gorm.DB, keyword string) (list []response.SearchList, err error) {
	err = db.Model(&f).
		Select("phone,nick_name,avatar_url,refer").
		Joins("LEFT JOIN users ON users.id = friends.friend_id").
		Where("users.phone like ? or users.nick_name like ?", "%"+keyword+"%", "%"+keyword+"%").
		Find(&list).Error
	return
}

func (f *Friend) GetFriend(db *gorm.DB, userId int) (list []response.FriendList, err error) {
	err = db.Model(&f).
		Select("phone,nick_name,avatar_url,refer,friends.created_at").
		Joins("LEFT JOIN users ON users.id = friends.friend_id").
		Where("friends.user_id = ?", userId).
		Find(&list).Error
	return
}
